<?php
include 'config.php';

// 处理公告添加
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_notice'])) {
    $notice_title = $_POST['notice_title'];
    $notice_text = $_POST['notice_text'];
    $publish_time = date('Y-m-d H:i:s');

    $stmt = $conn->prepare("INSERT INTO notices (notice_title, notice_text, publish_time) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $notice_title, $notice_text, $publish_time);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=add_notice");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理公告编辑
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_notice'])) {
    $id = $_POST['notice_id'];
    $notice_title = $_POST['notice_title'];
    $notice_text = $_POST['notice_text'];

    $stmt = $conn->prepare("UPDATE notices SET notice_title = ?, notice_text = ? WHERE id = ?");
    $stmt->bind_param("ssi", $notice_title, $notice_text, $id);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=edit_notice");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理公告删除
if (isset($_GET['delete_notice'])) {
    $id = $_GET['delete_notice'];
    $stmt = $conn->prepare("DELETE FROM notices WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=delete_notice");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理轮播图添加
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_slide'])) {
    $image_url = $_POST['image_url'];
    $stmt = $conn->prepare("INSERT INTO slides (image_url) VALUES (?)");
    $stmt->bind_param("s", $image_url);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=add_slide");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理轮播图编辑
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_slide'])) {
    $id = $_POST['slide_id'];
    $image_url = $_POST['image_url'];
    $stmt = $conn->prepare("UPDATE slides SET image_url = ? WHERE id = ?");
    $stmt->bind_param("si", $image_url, $id);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=edit_slide");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理轮播图删除
if (isset($_GET['delete_slide'])) {
    $id = $_GET['delete_slide'];
    $stmt = $conn->prepare("DELETE FROM slides WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=delete_slide");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理按钮添加
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_button'])) {
    $button_text = $_POST['button_text'];
    $link_url = $_POST['link_url'];
    $icon_path = null;

    if (isset($_FILES['icon']) && $_FILES['icon']['error'] === 0) {
        $target_dir = "uploads/";
        $original_filename = $_FILES["icon"]["name"];
        $file_extension = pathinfo($original_filename, PATHINFO_EXTENSION);
        $new_filename = uniqid() . '.' . $file_extension;
        $target_file = $target_dir . $new_filename;

        if (move_uploaded_file($_FILES["icon"]["tmp_name"], $target_file)) {
            $icon_path = $target_file;
        } else {
            $error = "上传图标时出错";
        }
    }

    $stmt = $conn->prepare("INSERT INTO buttons (button_text, link_url, icon_path) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $button_text, $link_url, $icon_path);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=add_button");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理按钮编辑
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_button'])) {
    $id = $_POST['button_id'];
    $button_text = $_POST['button_text'];
    $link_url = $_POST['link_url'];
    $icon_path = null;

    if (isset($_FILES['icon']) && $_FILES['icon']['error'] === 0) {
        $target_dir = "uploads/";
        $original_filename = $_FILES["icon"]["name"];
        $file_extension = pathinfo($original_filename, PATHINFO_EXTENSION);
        $new_filename = uniqid() . '.' . $file_extension;
        $target_file = $target_dir . $new_filename;

        if (move_uploaded_file($_FILES["icon"]["tmp_name"], $target_file)) {
            $icon_path = $target_file;
            $stmt = $conn->prepare("UPDATE buttons SET button_text = ?, link_url = ?, icon_path = ? WHERE id = ?");
            $stmt->bind_param("sssi", $button_text, $link_url, $icon_path, $id);
        } else {
            $error = "上传图标时出错";
        }
    } else {
        $stmt = $conn->prepare("UPDATE buttons SET button_text = ?, link_url = ? WHERE id = ?");
        $stmt->bind_param("ssi", $button_text, $link_url, $id);
    }

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=edit_button");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 处理按钮删除
if (isset($_GET['delete_button'])) {
    $id = $_GET['delete_button'];
    $stmt = $conn->prepare("DELETE FROM buttons WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        header("Location: admin.php?success=1&action=delete_button");
        exit;
    } else {
        $error = $stmt->error;
    }

    $stmt->close();
}

// 获取所有公告
$sql_notices = "SELECT * FROM notices";
$result_notices = $conn->query($sql_notices);

// 获取所有轮播图
$sql_slides = "SELECT * FROM slides";
$result_slides = $conn->query($sql_slides);

// 获取所有按钮
$sql_buttons = "SELECT * FROM buttons";
$result_buttons = $conn->query($sql_buttons);
?>

<?php
// ... 保持原有PHP代码不变 ...
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>管理页面 - 校园服务平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #6c5ce7;
            --secondary-color: #a8a4e6;
            --success-color: #00b894;
            --danger-color: #ff7675;
            --background-color: #f8f9fa;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        body {
            font-family: 'PingFang SC', 'Helvetica Neue', sans-serif;
            background-color: var(--background-color);
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .section-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            padding: 2rem;
            transition: transform 0.2s;
        }

        .section-card:hover {
            transform: translateY(-2px);
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--primary-color);
        }

        .section-title {
            font-size: 1.5rem;
            color: var(--primary-color);
            margin: 0;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: #555;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            transition: border-color 0.3s;
            font-size: 1rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(108, 92, 231, 0.1);
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
        }

        .btn-primary:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }

        .btn-danger:hover {
            background-color: #ff5252;
        }

        .btn-success {
            background-color: var(--success-color);
            color: white;
        }

        .table-responsive {
            overflow-x: auto;
            margin-top: 1.5rem;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        .data-table th,
        .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .data-table th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 500;
        }

        .data-table tr:hover {
            background-color: #f8f9ff;
        }

        .data-table tr:nth-child(even) {
            background-color: #fafafa;
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }

        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
        }

        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            position: relative;
        }

        .modal-close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
        }

        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }
            
            .section-card {
                padding: 1rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php
                $action = $_GET['action'];
                $messages = [
                    'add_notice' => '公告添加成功',
                    'edit_notice' => '公告更新成功',
                    'delete_notice' => '公告删除成功',
                    'add_slide' => '轮播图添加成功',
                    'edit_slide' => '轮播图更新成功',
                    'delete_slide' => '轮播图删除成功',
                    'add_button' => '按钮添加成功',
                    'edit_button' => '按钮更新成功',
                    'delete_button' => '按钮删除成功'
                ];
                echo $messages[$action] ?? '操作成功';
                ?>
            </div>
        <?php elseif (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                错误: <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <!-- 公告管理 -->
        <div class="section-card">
            <div class="section-header">
                <h2 class="section-title"><i class="fas fa-bullhorn"></i> 公告管理</h2>
                <button class="btn btn-primary" onclick="toggleForm('notice-form')">
                    <i class="fas fa-plus"></i> 添加公告
                </button>
            </div>
            <form method="post" id="notice-form" style="display: none;">
                <div class="form-group">
                    <label class="form-label" for="notice_title">公告标题</label>
                    <input type="text" class="form-control" id="notice_title" name="notice_title" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="notice_text">公告内容</label>
                    <textarea class="form-control" id="notice_text" name="notice_text" rows="4" required></textarea>
                </div>
                <button type="submit" name="add_notice" class="btn btn-success">
                    <i class="fas fa-save"></i> 保存公告
                </button>
            </form>
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>标题</th>
                            <th>内容</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $result_notices->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row["id"] ?></td>
                            <td><?= $row["notice_title"] ?></td>
                            <td><?= $row["notice_text"] ?></td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn btn-primary" 
                                            onclick="showEditNoticeModal(<?= $row['id'] ?>, '<?= addslashes($row['notice_title']) ?>', '<?= addslashes($row['notice_text']) ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a class="btn btn-danger" 
                                       href="?delete_notice=<?= $row['id'] ?>" 
                                       onclick="return confirm('确定要删除该公告吗？')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 轮播图管理 -->
        <div class="section-card">
            <div class="section-header">
                <h2 class="section-title"><i class="fas fa-images"></i> 轮播图管理</h2>
                <button class="btn btn-primary" onclick="toggleForm('slide-form')">
                    <i class="fas fa-plus"></i> 添加轮播图
                </button>
            </div>
            <form method="post" id="slide-form" style="display: none;">
                <div class="form-group">
                    <label class="form-label" for="image_url">图片URL</label>
                    <input type="text" class="form-control" id="image_url" name="image_url" required>
                </div>
                <button type="submit" name="add_slide" class="btn btn-success">
                    <i class="fas fa-save"></i> 保存设置
                </button>
            </form>
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>预览</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $result_slides->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row["id"] ?></td>
                            <td>
                                <img src="<?= $row["image_url"] ?>" alt="轮播图" style="max-width: 200px; height: auto; border-radius: 4px;">
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn btn-primary" 
                                            onclick="showEditSlideModal(<?= $row['id'] ?>, '<?= $row['image_url'] ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a class="btn btn-danger" 
                                       href="?delete_slide=<?= $row['id'] ?>" 
                                       onclick="return confirm('确定要删除该轮播图吗？')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 按钮管理 -->
        <div class="section-card">
            <div class="section-header">
                <h2 class="section-title"><i class="fas fa-hand-pointer"></i> 按钮管理</h2>
                <button class="btn btn-primary" onclick="toggleForm('button-form')">
                    <i class="fas fa-plus"></i> 添加按钮
                </button>
            </div>
            <form method="post" id="button-form" style="display: none;" enctype="multipart/form-data">
                <div class="form-group">
                    <label class="form-label" for="button_text">按钮文字</label>
                    <input type="text" class="form-control" id="button_text" name="button_text" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="link_url">跳转链接</label>
                    <input type="text" class="form-control" id="link_url" name="link_url" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="icon">图标上传</label>
                    <input type="file" class="form-control" id="icon" name="icon" accept="image/*">
                </div>
                <button type="submit" name="add_button" class="btn btn-success">
                    <i class="fas fa-save"></i> 保存按钮
                </button>
            </form>
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>按钮文字</th>
                            <th>跳转链接</th>
                            <th>图标</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $result_buttons->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row["id"] ?></td>
                            <td><?= $row["button_text"] ?></td>
                            <td><?= $row["link_url"] ?></td>
                            <td>
                                <?php if ($row["icon_path"]): ?>
                                <img src="<?= $row["icon_path"] ?>" alt="按钮图标" width="40" style="border-radius: 4px;">
                                <?php else: ?>
                                <span class="text-muted">无图标</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn btn-primary" 
                                            onclick="showEditButtonModal(<?= $row['id'] ?>, '<?= $row['button_text'] ?>', '<?= $row['link_url'] ?>', '<?= $row['icon_path'] ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a class="btn btn-danger" 
                                       href="?delete_button=<?= $row['id'] ?>" 
                                       onclick="return confirm('确定要删除该按钮吗？')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 编辑模态框 -->
        <div class="modal-overlay" id="editModal">
            <div class="modal">
                <button class="modal-close" onclick="closeModal()">&times;</button>
                <div id="modalContent"></div>
            </div>
        </div>
    </div>

    <script>
        // 通用函数
        function toggleForm(formId) {
            const form = document.getElementById(formId);
            form.style.display = form.style.display === 'none' ? 'block' : 'none';
        }

        function showModal(content) {
            document.getElementById('modalContent').innerHTML = content;
            document.getElementById('editModal').style.display = 'flex';
        }

        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 公告编辑
        function showEditNoticeModal(id, title, text) {
            const content = `
                <h3 style="margin-bottom: 1.5rem;">编辑公告</h3>
                <form onsubmit="event.preventDefault(); submitEditNotice(${id})">
                    <div class="form-group">
                        <label class="form-label">标题</label>
                        <input type="text" id="editNoticeTitle" class="form-control" value="${title.replace(/"/g, '&quot;')}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">内容</label>
                        <textarea id="editNoticeText" class="form-control" rows="4" required>${text}</textarea>
                    </div>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> 保存修改
                    </button>
                </form>
            `;
            showModal(content);
        }

        function submitEditNotice(id) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="notice_id" value="${id}">
                <input type="hidden" name="notice_title" value="${document.getElementById('editNoticeTitle').value}">
                <input type="hidden" name="notice_text" value="${document.getElementById('editNoticeText').value}">
                <input type="hidden" name="edit_notice" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        // 轮播图编辑
        function showEditSlideModal(id, url) {
            const content = `
                <h3 style="margin-bottom: 1.5rem;">编辑轮播图</h3>
                <form onsubmit="event.preventDefault(); submitEditSlide(${id})">
                    <div class="form-group">
                        <label class="form-label">图片URL</label>
                        <input type="text" id="editSlideUrl" class="form-control" value="${url}" required>
                    </div>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> 保存修改
                    </button>
                </form>
            `;
            showModal(content);
        }

        function submitEditSlide(id) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="slide_id" value="${id}">
                <input type="hidden" name="image_url" value="${document.getElementById('editSlideUrl').value}">
                <input type="hidden" name="edit_slide" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        // 按钮编辑（需要处理文件上传，此处需更复杂的实现）
        function showEditButtonModal(id, text, url, icon) {
            const content = `
                <h3 style="margin-bottom: 1.5rem;">编辑按钮</h3>
                <form onsubmit="event.preventDefault(); submitEditButton(${id})" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="form-label">按钮文字</label>
                        <input type="text" id="editButtonText" class="form-control" value="${text}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">跳转链接</label>
                        <input type="text" id="editButtonUrl" class="form-control" value="${url}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">更新图标</label>
                        <input type="file" id="editButtonIcon" class="form-control" name="icon">
                    </div>
                    ${icon ? `<p>当前图标: <img src="${icon}" width="40"></p>` : ''}
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> 保存修改
                    </button>
                </form>
            `;
            showModal(content);
        }

        function submitEditButton(id) {
            // 需要处理文件上传的复杂情况
            // 此处简化为传统表单提交
            const form = document.createElement('form');
            form.method = 'POST';
            form.enctype = 'multipart/form-data';
            form.innerHTML = `
                <input type="hidden" name="button_id" value="${id}">
                <input type="hidden" name="button_text" value="${document.getElementById('editButtonText').value}">
                <input type="hidden" name="link_url" value="${document.getElementById('editButtonUrl').value}">
                <input type="hidden" name="edit_button" value="1">
            `;
            // 处理文件上传
            const fileInput = document.getElementById('editButtonIcon');
            if(fileInput.files[0]) {
                const file = new File([fileInput.files[0]], fileInput.files[0].name);
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                const newFileInput = document.createElement('input');
                newFileInput.type = 'file';
                newFileInput.name = 'icon';
                newFileInput.files = dataTransfer.files;
                form.appendChild(newFileInput);
            }
            document.body.appendChild(form);
            form.submit();
        }
    </script>
</body>
</html>